import 'dart:async';
import 'dart:convert';

import 'package:web_socket_channel/web_socket_channel.dart';

typedef MessageCallable = dynamic Function(dynamic jsonObj);

class Global {
  static late WebSocketChannel channel;
  static var channelIsConnect = false;

  static final List<MessageCallable> _channelListenQueue = [];

  static int listenMessage(MessageCallable msgCallable) {
    var id = _channelListenQueue.length;
    _channelListenQueue.add(msgCallable);
    return id;
  }

  static removeListenMessage(int id) {
    return _channelListenQueue.removeAt(id);
  }

  static sendMessage(msg) {
    channel.sink.add(jsonEncode(msg));
  }

  static closeWebSocket() {
    if (channelIsConnect) {
      channel.sink.close();
    }
  }

  static String mdUser = '';
  static String mdPwd = '';
  static String websocketurl = 'ws://127.0.0.1:3001';

  static webSocketClient(String user, String pwd) {
    if (!channelIsConnect) {
      mdUser = user;
      mdPwd = pwd;
      channel = WebSocketChannel.connect(
          Uri.parse("$websocketurl/?user=$user&pwd=$pwd"));
      channelIsConnect = true;
      channel.stream.listen((message) {
        var msg = jsonDecode(message.toString());
        print('websocket-receive=${message.toString()}');
        for (var i = 0; i < _channelListenQueue.length; i++) {
          var ret = _channelListenQueue[i](msg);
          if (ret.runtimeType == bool && ret == false) {
            break;
          }
        }
      }, onError: (err) {
        channelIsConnect = false;
      }, onDone: () {
        channelIsConnect = false;
        //重连
        Timer(const Duration(seconds: 3), () {
          webSocketClient(mdUser, mdPwd);
        });
      });
    }
    return channel;
  }
}
